/**
 * Created with IntelliJ IDEA.
 * Description: leetcode: 2460. 对数组执行操作
 * <a href="https://leetcode.cn/problems/apply-operations-to-an-array/">...</a>
 * User: DELL
 * Date: 2023-10-12
 * Time: 22:31
 */
public class Solution {
    /**
     * 解题思路:
     * 分别进行两拨遍历,第一次遍历时更改数组的值,第二次遍历时将 0 移动到末尾,
     * 但是这样子写完后,发现这两次遍历可以合并,具体解法见 applyOperations2
     *
     * @param nums
     * @return
     */
    public int[] applyOperations(int[] nums) {
        // 题目保证数组长度大于2,因此不用校验
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                nums[i + 1] = 0;
            }
        }
        // 将 0 移到数组末尾
        int temp = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[temp++] = nums[i];
                if (temp != i + 1) {
                    nums[i] = 0;
                }
            }
        }
        return nums;
    }


    public int[] applyOperations2(int[] nums) {
        // 题目保证数组长度大于2,因此不用校验
        int temp = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                nums[i + 1] = 0;
                nums[i] = 2 * nums[i];
            }
            if (nums[i] != 0) {
                nums[temp++] = nums[i];
                if (temp != i + 1) {
                    nums[i] = 0;
                }
            }
        }
        nums[temp++] = nums[nums.length - 1];
        if (temp != nums.length) {
            nums[nums.length - 1] = 0;
        }
        return nums;
    }
}